package com.kun.aspect;

import com.kun.annotation.MethodPermissionCheck;
import com.kun.common.enumType.LevelEnum;
import com.kun.domain.TRolePermission;
import com.kun.service.util.UserContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.List;

@Aspect
@Component
public class PermissionCheckAspect {

    @Pointcut("@annotation(com.kun.annotation.MethodPermissionCheck)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object runSeep(ProceedingJoinPoint joinPoint) {
        List<TRolePermission> userPermission = UserContext.getUserPermission();
        MethodPermissionCheck declaredAnnotation = ((MethodSignature) joinPoint.getSignature()).getMethod()
                .getDeclaredAnnotation(MethodPermissionCheck.class);
        for (String string : declaredAnnotation.value()) {
            if (userPermission.stream().anyMatch(tRolePermission -> tRolePermission.getPermissions().contains(string))) {
                try {
                    return joinPoint.proceed();
                } catch (Throwable e) {
                    throw new RuntimeException("方法执行失败");
                }
            }
        }
        for (TRolePermission tRolePermission : userPermission) {
            LevelEnum role = declaredAnnotation.role();
            if (tRolePermission.getCode().equals(role.getName())) {
                try {
                    return joinPoint.proceed();
                } catch (Throwable e) {
                    throw new RuntimeException("方法执行失败");
                }
            }
        }

        // 判断是否角色控制
        throw new SecurityException("权限不足");
    }


}
